package org.ns.learn.rpc.codec;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DecodeUtils {
    
    public static Object toObject(Object parameter, ParameterType parameterType) {
        if (parameter == null) {
            return null;
        }
        Object value = parameter;
        // RpcRequest.ParameterType parameterType = parameterTypes[i];
        // 参数类型
        Class<?> type = parameterType.getParameterType();
        // 1 字符串类型
        if (type == String.class) {
            value = String.valueOf(value);
        }
        // 1 基本类型 数字类型
        else if (type == int.class || type == Integer.class) {
            value = ((Number)value).intValue();
        }
        else if (type == long.class || type == Long.class) {
            value = ((Number)value).longValue();
        }
        else if (type == short.class || type == Short.class) {
            value = ((Number)value).shortValue();
        }
        else if (type == double.class || type == Double.class) {
            value = ((Number)value).doubleValue();
        }
        else if (type == float.class || type == Float.class) {
            value = ((Number)value).floatValue();
        }
        else if (type == byte.class || type == Byte.class) {
            value = ((Number)value).byteValue();
        }
        else if (type == char.class || type == Character.class) {
            String str = String.valueOf(value);
            if (str.isEmpty()) {
                value = '\0';
            } else {
                value = String.valueOf(value).charAt(0);
            }
        }
        else if (type == BigDecimal.class) {
            value = value instanceof BigDecimal ? value : new BigDecimal(value.toString());
        }
        // 2 日期类型
        else if (type == Date.class) {
            value = new Date(((Number)value).longValue());
        }
        else if (type == java.sql.Date.class) {
            value = new java.sql.Date(((Number)value).longValue());
        }
        // 3 自定义类型
        else if (value instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) value;
            value = jsonObject.toJavaObject(type);
        }
        else if (value instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) value;
            if (jsonArray.size() > 0) {
                List<?> list = JSON.parseArray(jsonArray.toJSONString(), parameterType.getComponentType());

                if (type == Set.class || type == HashSet.class) {
                    value = new HashSet<>(list);
                } else {
                    value = list;
                }

            } else {

            }
        } else {
            value = null;
            System.err.println("暂不支持这个类型: " + type);
        }
        return value;
    } 
    
}
